<?php
/**
 * 批假及详情页
 * 实现如果是审核人就可以批准和驳回,审请人自己可以查看
 * **/
apf_require_controller('Oa_Attendance_Abstract');
apf_require_class('Bll_Attendance_UserInfo');
apf_require_class('Bll_Attendance_LeaveRecord');
apf_require_class('Bll_Attendance_Audit');
apf_require_class('Bll_Attendance_ApplyType');
apf_require_class('Bll_Attendance_AccessDayRecord');

class Oa_Attendance_ApplyDetailController extends Oa_Attendance_AbstractController {

    public function handle_request() {
        $params = $this->request->get_parameters();
        $user_id = $_SESSION['user_id'];
        $leave_id =$params['id'];
        //check
        if(empty($leave_id)){
            $this->apf->get_response()->redirect('/',false,false);
        }
        //请假记录
        $bll_leave = new Bll_Attendance_LeaveRecord();
        $data_leave = $bll_leave->get_leave_by_id($leave_id);

        $hr = $this->control_permission($data_leave);
        $check_user = array($data_leave['user_id'],$data_leave['r_user_id'],$data_leave['b_user_id']);
        if($hr == 3) {
            $check_user = array_merge($check_user,array($user_id));
        }
        if($data_leave['type']=='出差'){//出差特殊处理
            apf_require_class('Bll_Attendance_Trip');
            $bll_trip = new Bll_Attendance_Trip();
            apf_require_class('Bll_Login_User');
            $user_bll = new Bll_Login_User;
            $tmp_uinfo = $user_bll->get_user_info_by_ids(array($data_leave['user_id']));
            $tmp_uinfo = $tmp_uinfo[$data_leave['user_id']];
            $u_data = $bll_trip->get_dpt_by_id($tmp_uinfo['department_id']);
            $dpt_uid = $u_data['user_id'];
            $check_user = array_merge($check_user,array($dpt_uid));
        }
        if(!in_array($user_id,$check_user)){//没有查看权限
            $this->apf->get_response()->redirect('/',false,false);
        }

        if($this->request->get_method() == 'POST'){
           $bll_audit = new Bll_Attendance_Audit();
           if(isset($params['apply']) && $params['apply']=='批 准'){
               $bll_audit->audit_apply($user_id, $params['id'],$_POST);
           }elseif(isset($params['apply1']) && $params['apply1']=='驳 回'){
               $bll_audit->aduit_reject($user_id, $params['id'],$_POST);
           }
           $this->apf->get_response()->redirect('/audit/',false,false);
        }
        $is_agent=0;//是否显示代理人
        $typelist = Bll_Attendance_ApplyType::get_leave_type();
        if(in_array($data_leave['type'], $typelist)){
            $is_agent=1;
        }
        $data_leave['leave_time'] = abs($data_leave['leave_time']);
        $data_leave['access_date'] = substr($data_leave['start_time'],0,10);
        //迟到 早退
        if($data_leave['type']=='迟到' || $data_leave['type']=='早退' || $data_leave['type']=='缺勤'){
            $data_leave['work_status'] = $this->get_late_info($data_leave['user_id'],$data_leave['access_date']);
        }

        //是否有图片
        if(!empty($data_leave['img'])){
            $data_leave['img'] = "/upload/attendance/".$data_leave['img'];
        }
        //请假者个人信息
        $bll_user = new Bll_Attendance_UserInfo();
        $data_user = $bll_user->get_user_by_ids(array($data_leave['user_id']));

        $show_special=1;
        if($data_leave['user_id'] == $user_id){//是请假者自己看详情时不显示部分信息
            $show_special=0;
        }
        $user_all_annual= array();
        if($data_leave['type']=='年假'){
            $user_all_annual = $this->get_all_annual($data_leave['user_id']);//今年还有多少年假
        }
        //出差-打印
        if($data_leave['type']=='出差'){
            $print_url = Tools_OAUrls::get_instance()->build_print_url_list($data_leave['id']);
            $this->request->set_attribute('print_url',$print_url);
        }
        //已审批页面
        if($data_leave['user_id']==$_SESSION['user_id']){
            $unaudit_url = Tools_OAUrls::get_instance()->build_myapply_url();
        }else{
            $unaudit_url = Tools_OAUrls::get_instance()->build_unaudit_list();
        }
        $this->request->set_attribute('unaudit_url',$unaudit_url);
        //从今天开始近3个月请假详细
        $data_record = array();
        if($show_special){
            $data_record = $this->get_le_record_self($bll_leave,$data_leave['user_id']);
        }

        apf_require_class('Bll_Attendance_LeaveRecordLog');
        $LeaveRecordLog = new Bll_Attendance_LeaveRecordLog();
        $LeaveRecordLog_list = $LeaveRecordLog->get_log_by_ids($leave_id);
        $cannt_approve = 0;
        $action = array('1'=> '已驳回','2'=> '已批准');
        $level = array('1' => '一级','2' => '二级','3' => '');
        $need_two = $data_leave['leave_time'] > 3?1:0;
        foreach ($LeaveRecordLog_list as $key => $val) {
            //$temp[$val['operator']] = array('status' => $action[$val['action']],'msg' => $val['apply_msg'],'level' =>$check_level);
            if($val['operator'] == $data_leave['r_user_id']) {
                $check_level = $need_two == 1?$level[1]:$level[3];
                $admin_msg['first'] = array('status' => $action[$val['action']],'msg' => $val['apply_msg'],'level' =>$check_level);
            }
            if($val['operator'] == $data_leave['b_user_id']) {
                $check_level = $need_two == 1?$level[2]:$level[3];
                $admin_msg['second'] = array('status' => $action[$val['action']],'msg' => $val['apply_msg'],'level' =>$check_level);
            }
        }
        //是否为一级批假人
        $admin_msg['first']['as'] = $supperor = $this->uinfo['user_id'] == $data_leave['r_user_id']?1:0;
        //是否为二级批假人
        $admin_msg['second']['as'] = $supperor = $this->uinfo['user_id'] == $data_leave['b_user_id']?1:0;
        if($data_leave['type']=='出差' && $dpt_uid){//出差直接由最大部门负责人审核
            //$admin_msg['first']['as'] = $supperor = $this->uinfo['user_id'] == $dpt_uid ?1:0;
        }

        $this->request->set_attribute('user_all_annual',$user_all_annual);
        $this->request->set_attribute('njyear',date('Y'));
        $this->request->set_attribute('data_record',$data_record);
        $this->request->set_attribute('cannt_approve',$cannt_approve);
        $this->request->set_attribute('is_agent',$is_agent);
        $this->request->set_attribute('show_special',$show_special);
        $this->request->set_attribute('data_leave',$data_leave);
        $this->request->set_attribute('LeaveRecordLog_list',$admin_msg);
        $this->request->set_attribute('admin_msg',$admin_msg);
        $this->request->set_attribute('data_user',$data_user[$data_leave['user_id']]);

        return 'Oa_Attendance_ApplyDetail';
    }

    //根据leave_id获取leave_record_log记录，即：获取用户的审批mgs
    private function get_leave_record_log($leave_id){
        $leave_record_log = new Bll_Attendance_LeaveRecordLog();
        $result = $leave_record_log->get_log_by_ids($leave_id);
        return $result;
    }

     /**
     * 权限控制，非本人，或者一二级审核人，不能查看对应的详情页
     * @param $data_leave array
     * @author coldarmy
     * ***/
    private function control_permission($data_leave) {
        $check = true;
        if(empty($data_leave)){
            $this->apf->get_response()->redirect('/',false,false);
        }
        if($this->uinfo['user_id'] == $data_leave['user_id']) {

        } elseif ($this->uinfo['user_id'] == $data_leave['r_user_id']) {

        } elseif ($this->uinfo['user_id'] == $data_leave['b_user_id']) {

        } else {
            //对hr做特殊处理
            apf_require_class("Bll_Attendance_UserInfo");
            $bll_user = new Bll_Attendance_UserInfo();
            $role = $bll_user->get_user_role($this->uinfo['user_id']);
            if($role[$this->uinfo['user_id']]['role_id'] == 3){
                return 3;
            }
        }
    }

    //获取某个用户最近三个月的请假记录
    private function get_le_record_self($bll_leave,$user_id){
        $three_start = strtotime("-3 month");
        $where['apply_time_ext > '.$three_start.' AND user_id = '.$user_id.' AND 1=?'] =1;
        $data_record = $bll_leave->get_leave_record_data($where,$limit = 100,$page = 1,$order = 'id desc');
        foreach($data_record as $k=> $val){
            if($val['status']=='已撤销'){
                unset($data_record[$k]);continue;
            }
            $day = substr($val['start_time'],0,10);
            $data_record[$k]['access_date'] = $day;
            $data_record[$k]['work_status'] = $this->get_late_info($user_id,$day);
        }
        return $data_record;
    }
    private function calculate_annual_days($user_id){
        apf_require_class("Tools_Tools");
        $tools = Tools_Tools::get_instance();
        apf_require_class("Bll_Attendance_UserInfo");
        $bll_info = new Bll_Attendance_UserInfo();
        $userinfo = $bll_info->get_user_by_ids($user_id);
        $enterdate = $userinfo[0]['enter_date'];
        $day = $tools->annual($enterdate);
        if($day <=0){
            return 0;
        }else{
            apf_require_class("Bll_Attendance_UserExt");
            $bll_ext = new Bll_Attendance_UserExt;
            $used_day = $bll_ext->get_used_annual($user_id);
        }
        return max(($day-$used_day),0);
    }
    //迟到 早退
    private function get_late_info($uid,$day){
        $day = str_replace('-','',$day);
        $re_bll = new Bll_Attendance_AccessDayRecord();
        $data = $re_bll->get_user_day($uid,$day);
        if(!empty($data)){
            $data = $data[0];
            $data['status'] = $re_bll->check_day_work_status($day,$data['start_work'],$data['end_work']);
            $data['start_work']=substr($data['start_work'], 0,2).':'.substr($data['start_work'], 2,2);
            $data['end_work']=substr($data['end_work'], 0,2).':'.substr($data['end_work'], 2,2);

            if ($data['status'][0] == 3 && $data['status'][1] == 4) {
                //全天缺勤;
                $data['day_type'] = '全天';
                $data['day'] = 1;
            }elseif ($data['status'][0] == 3){
                //上午缺勤
                $data['day_type'] = '上午';
                $data['day'] = 0.5;
            }elseif ($data['status'][0] == 4){
                //下午缺勤
                $data['day_type'] = '下午';
                $data['day'] = 0.5;
            }

        }
        if(empty($data)||!isset($data['day']))
        {
            $data['day_type'] = '';
            $data['day']=0;
        }
        return $data;
    }

}
